package x.ovo.wechat.bot.common.http.session;

import lombok.Data;
import x.ovo.wechat.bot.common.entity.Contact;
import x.ovo.wechat.bot.common.http.request.BaseRequest;

import java.io.Serializable;
import java.net.HttpCookie;
import java.util.List;
import java.util.Objects;

/**
 * 登录会话
 * <p>
 *
 * @author ovo on 2024/04/19.
 * @since 1.0.0
 */
@Data
public class LoginSession implements Serializable {

    /** 用户信息 */
    private Contact contact;
    /** 用户名 */
    private String userName;
    /** 昵称 */
    private String nickName;

    /** 网址 */
    private String url;
    /** 文件 URL */
    private String fileUrl;
    /** 同步 URL */
    private String syncUrl;
    /** 设备 ID */
    private String deviceId;
    /** S 键 */
    private String sKey;
    /** WX SID */
    private String wxSid;
    /** WX UIN */
    private String wxUin;

    /** 邀请开始计数 */
    private Integer inviteStartCount;
    /** 基本请求 */
    private BaseRequest baseRequest;
    /** 同步密钥 */
    private SyncKey syncKey;
    /** 同步检查密钥 */
    private SyncKey syncCheckKey;

    private String dataTicket;
    private String passTicket;
    private String authTicket;
    private long lastExitTime = 0;

    public void init(BaseRequest baseRequest, List<HttpCookie> cookies) {
        this.baseRequest = baseRequest;
        this.sKey = baseRequest.getSkey();
        this.wxSid = baseRequest.getSid();
        this.wxUin = baseRequest.getUin();
        this.deviceId = baseRequest.getDeviceID();

        String domain = "wx.qq.com";
        if (null != cookies && !cookies.isEmpty()) {
            domain = cookies.stream()
                    .map(HttpCookie::getDomain)
                    .filter(Objects::nonNull)
                    .filter(cookie -> !cookie.startsWith("."))
                    .findFirst()
                    .orElse("wx.qq.com");
        }
        this.url = "https://" + domain;
        this.syncUrl = "https://" + domain;
        this.fileUrl = "https://file." + domain;
    }
}
